<template>
  <div class="multi-chat-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar" :class="{ 'sidebar-hidden': !sidebarVisible }">
      <!-- 用户信息区域 -->
      <div class="user-profile">
        <div class="user-avatar-wrapper">
          <a-avatar
            :size="48"
            :src="userStore.profile?.avatar"
            :style="userStore.profile?.avatar ? {} : { backgroundColor: '#6366f1', color: 'white' }"
          >
            {{ (userStore.profile?.nickname || userStore.profile?.username || '用户')[0]?.toUpperCase() || 'U' }}
          </a-avatar>
          <div class="online-status"></div>
        </div>
        <div class="user-info">
          <div class="user-name">{{ userStore.profile?.nickname || userStore.profile?.username || '用户' }}</div>
          <div class="user-status">在线</div>
        </div>
      </div>

      <!-- 创建聊天室按钮 -->
      <div class="create-room-section">
        <Button
          type="primary"
          block
          size="large"
          @click="createNewRoom"
          class="create-room-btn"
        >
          <template #icon>
            <Plus :size="18" />
          </template>
          创建聊天室
        </Button>
      </div>

      <!-- 聊天室列表 -->
      <div class="rooms-section">
        <div class="section-title">聊天室</div>
        <div class="rooms-list">
          <!-- 加载状态 -->
          <div v-if="loading && chatRooms.length === 0" class="loading-state">
            <div class="loading-spinner"></div>
            <span>加载中...</span>
          </div>

          <!-- 聊天室列表 -->
          <div
            v-for="room in chatRooms"
            :key="room.id"
            class="room-item"
            :class="{ 'room-active': room.id?.toString() === currentRoomId }"
            @click="switchRoom(room.id?.toString() || '')"
          >
            <div class="room-avatar">
              <MessageSquare :size="20" />
            </div>
            <div class="room-content">
              <div class="room-header">
                <span class="room-name">{{ room.name }}</span>
                <div class="room-actions">
                  <Button
                    type="text"
                    size="small"
                    class="action-btn edit-btn"
                    @click.stop="editRoom(room)"
                    title="编辑聊天室"
                  >
                    <Edit :size="14" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    class="action-btn delete-btn"
                    @click.stop="deleteRoom(room)"
                    title="删除聊天室"
                  >
                    <Trash2 :size="14" />
                  </Button>
                  <span class="room-time">{{ room.lastMessageTime ? formatTime(room.lastMessageTime) : '' }}</span>
                </div>
              </div>
              <div class="room-preview">
                <span class="last-message">{{ room.description || '没有留下任何简介呢~' }}</span>
                <span v-if="(room.unreadCount || 0) > 0" class="unread-badge">{{ room.unreadCount }}</span>
              </div>
            </div>
          </div>

          <!-- 加载更多按钮 -->
          <div v-if="hasMore && chatRooms.length > 0" class="load-more-section">
            <Button
              type="text"
              block
              :loading="loading"
              @click="loadMoreRooms"
              class="load-more-btn"
            >
              {{ loading ? '加载中...' : '加载更多' }}
            </Button>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && chatRooms.length === 0" class="empty-rooms">
            <Empty
              :image="Empty.PRESENTED_IMAGE_SIMPLE"
              description="暂无聊天室"
            >
              <template #description>
                <span class="empty-description">暂无聊天室</span>
                <div class="empty-tip">点击上方按钮创建第一个聊天室</div>
              </template>
            </Empty>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航栏 -->
      <div class="chat-header">
        <div class="header-left">
          <div class="current-room-info">
            <h3 class="room-title">{{ currentRoom?.name || '选择聊天室' }}</h3>
            <span class="room-members">{{ onlineUsers.length }} 人在线</span>
          </div>
          <!-- 在线角色展示 - 横向布局 -->
          <OnlineRoles
            v-if="currentRoomId"
            :room-id="currentRoomId"
            :horizontal="true"
            class="online-roles-horizontal"
            @roles-updated="handleRolesUpdated"
            @role-click="handleRoleClick"
          />
        </div>
        <div class="header-right">
          <Button
            type="text"
            @click="showRoleSelection = true"
            class="role-btn"
            title="选择角色"
          >
            <Users :size="20" />
          </Button>

        </div>
      </div>

      <!-- 聊天内容区域 -->
      <div class="chat-content" ref="chatContentRef">
        <div v-if="!currentRoomId" class="empty-state">
          <MessageCircle :size="64" class="empty-icon" />
          <h3>欢迎使用多人聊天</h3>
          <p>选择一个聊天室开始对话，或创建新的聊天室</p>
        </div>

        <div v-else class="messages-container">
          <!-- 历史消息加载指示器 -->
          <div
            v-if="currentRoomId && messagePageInfo[currentRoomId]?.loading && messagePageInfo[currentRoomId]?.pageNo > 1"
            class="loading-more-messages"
          >
            <div class="loading-spinner"></div>
            <span class="loading-text">加载更多消息...</span>
          </div>

          <div
            v-for="message in currentMessages"
            :key="message.id"
            class="message-wrapper"
            :class="{
              'message-left': message.senderType === 1,
              'message-right': message.senderType === 0
            }"
          >
            <!-- AI角色消息：左侧头像 + 消息内容 -->
            <template v-if="message.senderType === 1">
              <div class="message-avatar">
                <a-avatar
                  :size="32"
                  :src="message.avatarUrl"
                  :style="message.avatarUrl ? {} : { backgroundColor: getUserColor(message.userId), color: 'white' }"
                >
                  {{ (message.roleName || '角色')[0]?.toUpperCase() || 'U' }}
                </a-avatar>
              </div>

              <div class="message-content">
                <div class="message-info">
                  <span class="sender-name" :style="{ color: getUserColor(message.userId) }">
                    {{ message.roleName }}
                  </span>
                  <span class="message-time">{{ formatMessageTime(message.timestamp) }}</span>
                </div>

                <div class="message-bubble bubble-ai">
                  {{ message.content }}
                </div>
              </div>
            </template>

            <!-- 用户消息：消息内容 + 右侧头像 -->
            <template v-else>
              <div class="message-content">
                <div class="message-bubble bubble-user">
                  {{ message.content }}
                </div>

                <div class="message-time-user">
                  {{ formatMessageTime(message.timestamp) }}
                </div>
              </div>

              <div class="message-avatar">
                <a-avatar
                  :size="32"
                  :src="userStore.profile?.avatar"
                  :style="userStore.profile?.avatar ? {} : { backgroundColor: '#6366f1', color: 'white' }"
                >
                  {{ (userStore.profile?.nickname || userStore.profile?.username || '我')[0]?.toUpperCase() || 'U' }}
                </a-avatar>
              </div>
            </template>
          </div>

          <!-- 正在输入指示器 -->
          <div v-if="typingUsers.length > 0" class="typing-indicator">
            <div class="typing-dots">
              <div class="dot"></div>
              <div class="dot"></div>
              <div class="dot"></div>
            </div>
            <span class="typing-text">{{ getTypingText() }}</span>
          </div>
        </div>
      </div>

      <!-- 底部输入区域 -->
      <div v-if="currentRoomId">
        <ChatInputBox
          v-model="messageInput"
          :loading="isSending || isAiProcessing"
          :disabled="isSending || isAiProcessing"
          :is-voice-recording="isVoiceRecording"
          @send="sendMessage"
          @transcription-update="handleTranscriptionUpdate"
          @recording-start="handleRecordingStart"
          @recording-stop="handleRecordingStop"
          @voice-error="handleVoiceError"
          @input="handleTyping"
          ref="chatInputRef"
        />

        <!-- AI处理状态提示 -->
        <div v-if="isAiProcessing" class="ai-processing-indicator">
          <div class="processing-content">
            <div class="processing-spinner"></div>
            <span class="processing-text">AI角色正在思考中...</span>
            <span class="processing-roles" v-if="aiProcessingRoles.length > 0">
              ({{ aiProcessingRoles.length }} 个角色参与)
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建聊天室弹窗 -->
    <CreateRoomModal
      v-model:open="showCreateRoom"
      @create="handleCreateRoom"
    />

    <!-- 角色选择弹窗 -->
    <RoleSelectionModal
      v-model:open="showRoleSelection"
      :room-id="currentRoomId"
      @submit="handleRoleSelectionSubmit"
    />

    <!-- 编辑聊天室弹窗 -->
    <EditRoomModal
      v-model:visible="showEditRoom"
      :room-data="currentEditRoom ? {
        id: currentEditRoom.id || '',
        name: currentEditRoom.name || '',
        description: currentEditRoom.description,
        autoTalkEnabled: currentEditRoom.autoTalkEnabled
      } : undefined"
      @success="handleEditSuccess"
    />

    <!-- 删除聊天室弹窗 -->
    <DeleteRoomModal
      v-model:visible="showDeleteRoom"
      :room-id="currentDeleteRoom?.id"
      :room-name="currentDeleteRoom?.name"
      @success="handleDeleteSuccess"
    />

    <!-- 角色信息弹窗 -->
    <RoleInfoModal
      v-model:open="showRoleInfo"
      :role-info="currentSelectedRole"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch, onBeforeUnmount } from 'vue'
import { Button, message, Empty, Modal } from 'ant-design-vue'
import { Plus, MessageSquare, MessageCircle, Edit, Trash2, Users } from 'lucide-vue-next'
import { useRouter } from 'vue-router'
import { useUserStore, useAuthStore } from '@/stores'
import CreateRoomModal from '@/components/MultiChat/CreateRoomModal.vue'
import RoleSelectionModal from '@/components/MultiChat/RoleSelectionModal.vue'
import ChatInputBox from '@/components/MultiChat/ChatInputBox.vue'
import EditRoomModal from '@/components/MultiChat/EditRoomModal.vue'
import DeleteRoomModal from '@/components/MultiChat/DeleteRoomModal.vue'
import OnlineRoles from '@/components/MultiChat/OnlineRoles.vue'
import RoleInfoModal from '@/components/MultiChat/RoleInfoModal.vue'
import { Codewin } from '@/api/generated/Codewin'
import type {
  ChatRoomPageRequest,
  CreateChatRoomRequest,
  ChatRoomVO,
  ChatRoomMessageInsertRequest
} from '@/api/generated/data-contracts'

defineOptions({ name: 'MultiChat' })

const router = useRouter()
const userStore = useUserStore()

// API 实例
const authStore = useAuthStore()
const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top',
  securityWorker: (securityData) => {
    return authStore.token ? { headers: { Authorization: `Bearer ${authStore.token}` } } : {}
  }
})

// 响应式状态
const sidebarVisible = ref(true)
const showCreateRoom = ref(false)
const showRoleSelection = ref(false)
const showEditRoom = ref(false)
const showDeleteRoom = ref(false)
const showRoleInfo = ref(false)
const isVoiceRecording = ref(false)
const messageInput = ref('')
const isSending = ref(false)
const chatContentRef = ref<HTMLElement>()
const chatInputRef = ref()

// 当前操作的聊天室
const currentEditRoom = ref<ChatRoomVO | null>(null)
const currentDeleteRoom = ref<ChatRoomVO | null>(null)
const currentSelectedRole = ref<any>(null)

// 分页和加载状态
const loading = ref(false)
const pageParam = ref<ChatRoomPageRequest>({
  pageNo: 1,
  pageSize: 20,
  name: '',
  description: ''
})
const totalRooms = ref(0)
const hasMore = ref(true)

// 聊天室数据
const chatRooms = ref<Array<ChatRoomVO & { lastMessage?: string; lastMessageTime?: Date; unreadCount?: number }>>([])

const currentRoomId = ref<string>('')
const currentRoom = computed(() => chatRooms.value.find(room => room.id === currentRoomId.value))

// 消息数据
const messages = ref<Record<string, Array<{
  id: string
  content: string
  userId: string
  userName: string
  userAvatar?: string
  senderType?: number
  roleName?: string
  avatarUrl?: string
  timestamp: Date
}>>>({})

const currentUserId = computed(() => userStore.profile?.id || 'current_user')
const typingUsers = ref<Array<{ id: string, name: string }>>([])

const currentMessages = computed(() => {
  const messageList = messages.value[currentRoomId.value] || []
  return [...messageList].sort((a, b) => {
    const timeA = new Date(a.timestamp).getTime()
    const timeB = new Date(b.timestamp).getTime()
    return timeA - timeB
  })
})

const onlineUsers = ref<Array<{
  id: string
  username: string
  nickname: string
  avatar: string
  status: 'online' | 'offline'
  isMuted: boolean
}>>([])

const handleRolesUpdated = (roles: any[]) => {
  onlineUsers.value = roles.map(role => ({
    id: role.id,
    username: role.name,
    nickname: role.name,
    avatar: role.avatar || '',
    status: 'online' as const,
    isMuted: false
  }))
}

// 处理角色点击事件
const handleRoleClick = (role: any) => {
  currentSelectedRole.value = role
  showRoleInfo.value = true
}

// 用户颜色
const userColors = ['#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f59e0b', '#10b981', '#06b6d4', '#3b82f6']

let typingTimer: number | null = null

// 工具函数
const getUserColor = (userId: string) => {
  const hash = userId.split('').reduce((a, b) => {
    a = ((a << 5) - a) + b.charCodeAt(0)
    return a & a
  }, 0)
  return userColors[Math.abs(hash) % userColors.length]
}

const formatTime = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
}

const formatMessageTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const getTypingText = () => {
  if (typingUsers.value.length === 1) {
    const firstUser = typingUsers.value[0]
    return firstUser ? `${firstUser.name || ''} 正在输入...` : ''
  } else if (typingUsers.value.length === 2) {
    const firstUser = typingUsers.value[0]
    const secondUser = typingUsers.value[1]
    return (firstUser && secondUser) ? `${firstUser.name || ''} 和 ${secondUser.name || ''} 正在输入...` : ''
  } else if (typingUsers.value.length > 0) {
    return `${typingUsers.value.length} 人正在输入...`
  } else {
    return ''
  }
}

// API 调用方法
const fetchChatRooms = async (loadMore = false) => {
  if (loading.value) return

  try {
    loading.value = true

    if (!loadMore) {
      pageParam.value.pageNo = 1
      chatRooms.value = []
    }

    const response = await api.getMyChatRoomList({ pageParam: pageParam.value })

    if (response.data?.code === 0 && response.data.data) {
      const { list, total } = response.data.data

      if (loadMore) {
         chatRooms.value.push(...(list || []).map((room: ChatRoomVO) => ({
           ...room,
           lastMessage: '',
           lastMessageTime: room.updatedAt ? new Date(room.updatedAt) : undefined,
           unreadCount: 0
         })))
       } else {
         chatRooms.value = (list || []).map((room: ChatRoomVO) => ({
           ...room,
           lastMessage: '',
           lastMessageTime: room.updatedAt ? new Date(room.updatedAt) : undefined,
           unreadCount: 0
         }))
       }

      totalRooms.value = total || 0
      hasMore.value = chatRooms.value.length < totalRooms.value

      if (!currentRoomId.value && chatRooms.value.length > 0) {
        const firstRoom = chatRooms.value[0]
        const firstRoomId = firstRoom?.id?.toString() || ''
        if (firstRoomId) {
          currentRoomId.value = firstRoomId
          await fetchChatRoomMessages(firstRoomId)
          nextTick(() => {
            scrollToBottom()
          })
        }
      }
    } else {
      message.error(response.data?.message || '获取聊天室列表失败')
    }
  } catch (error) {
    message.error('获取聊天室列表失败')
  } finally {
    loading.value = false
  }
}

const loadMoreRooms = async () => {
  if (!hasMore.value || loading.value) return

  pageParam.value.pageNo += 1
  await fetchChatRooms(true)
}



const createNewRoom = () => {
  showCreateRoom.value = true
}

const handleCreateRoom = async (data: { name: string; description: string; autoTalkEnabled: boolean }) => {
  try {
    const createRequest = {
      name: data.name,
      description: data.description,
      autoTalkEnabled: data.autoTalkEnabled ? 1 : 0
    } as CreateChatRoomRequest & { autoTalkEnabled: number }

    const response = await api.createChatRoom(createRequest)

    if (response.data?.code === 0 && response.data.data) {
      message.success('聊天室创建成功')
      await fetchChatRooms()

      const newRoomId = response.data.data.toString()
      if (newRoomId) {
        switchRoom(newRoomId)
      }
    } else {
      message.error(response.data?.message || '创建聊天室失败')
    }
  } catch (error) {
    message.error('创建聊天室失败')
  }
}

// 编辑聊天室
const editRoom = (room: ChatRoomVO) => {
  currentEditRoom.value = room
  showEditRoom.value = true
}

// 删除聊天室
const deleteRoom = (room: ChatRoomVO) => {
  currentDeleteRoom.value = room
  showDeleteRoom.value = true
}

// 处理编辑成功
const handleEditSuccess = async () => {
  await fetchChatRooms()
}

// 处理删除成功
const handleDeleteSuccess = async () => {
  if (currentDeleteRoom.value?.id?.toString() === currentRoomId.value) {
    currentRoomId.value = ''
  }
  await fetchChatRooms()
}

// 消息分页状态
const messagePageInfo = ref<Record<string, { pageNo: number; hasMore: boolean; loading: boolean }>>({})

// 获取聊天室消息
const fetchChatRoomMessages = async (roomId: string, loadMore = false) => {
  try {
    // 初始化分页信息
    if (!messagePageInfo.value[roomId]) {
      messagePageInfo.value[roomId] = { pageNo: 1, hasMore: true, loading: false }
    }

    const pageInfo = messagePageInfo.value[roomId]

    // 如果正在加载或没有更多数据，直接返回
    if (pageInfo.loading || (!loadMore && !pageInfo.hasMore && messages.value[roomId]?.length > 0)) {
      return
    }

    pageInfo.loading = true

    const currentPageNo = loadMore ? pageInfo.pageNo + 1 : 1

    const response = await api.getChatRoomMessages({
      roomId: roomId,
      pageNo: currentPageNo,
      pageSize: 20
    })

    if (response.data?.code === 0 && response.data.data?.list) {
      const messageList = response.data.data.list.map((msg: any) => ({
        id: msg.id?.toString() || Date.now().toString(),
        content: msg.content || '',
        userId: msg.userId?.toString() || '',
        userName: msg.userName || '未知用户',
        userAvatar: msg.userAvatar || '',
        senderType: msg.senderType || 0,
        roleName: msg.roleName || '',
        avatarUrl: msg.avatarUrl || '',
        timestamp: msg.createdAt ? new Date(msg.createdAt) : new Date()
      }))

      if (loadMore) {
        // 加载更多时，将新消息插入到现有消息列表的开头
        if (!messages.value[roomId]) {
          messages.value[roomId] = []
        }
        messages.value[roomId] = [...messageList, ...messages.value[roomId]]
        pageInfo.pageNo = currentPageNo
      } else {
        // 初始加载时，直接设置消息列表
        messages.value[roomId] = messageList
        pageInfo.pageNo = 1
      }

      // 更新是否还有更多数据
      pageInfo.hasMore = messageList.length === 20
    } else {
      if (!loadMore) {
        messages.value[roomId] = []
      }
    }
  } catch (error) {
    if (!loadMore) {
      messages.value[roomId] = []
    }
  } finally {
    if (messagePageInfo.value[roomId]) {
      messagePageInfo.value[roomId].loading = false
    }
  }
}

// 显示离开确认对话框
// 重置对话状态
const resetConversationState = () => {
  // 清理WebSocket连接和定时器
  cleanupWebSockets()
  if (autoTalkTimer.value) {
    clearTimeout(autoTalkTimer.value)
    autoTalkTimer.value = null
  }
  if (typingTimer) {
    clearTimeout(typingTimer)
    typingTimer = null
  }

  // 重置状态变量
  isAiProcessing.value = false
  aiProcessingRoles.value = []
  isSending.value = false
  lastUserMessageTime.value = null
}

const showLeaveConfirmDialog = (action: () => void, title = '切换聊天室') => {
  Modal.confirm({
    title: `确认${title}`,
    content: `当前正在进行AI对话，${title}将会中断对话进程。确定要继续吗？`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk() {
      // 重置对话状态
      resetConversationState()

      // 执行原始操作
      action()
    }
  })
}

const switchRoom = async (roomId: string) => {
  // 如果正在对话中，显示确认对话框
  if (isInConversation.value && currentRoomId.value !== roomId) {
    showLeaveConfirmDialog(async () => {
      await performRoomSwitch(roomId)
    }, '切换聊天室')
    return
  }

  await performRoomSwitch(roomId)
}

// 执行实际的聊天室切换
const performRoomSwitch = async (roomId: string) => {
  currentRoomId.value = roomId

  const room = chatRooms.value.find(r => r.id?.toString() === roomId)
  if (room && room.unreadCount !== undefined) {
    room.unreadCount = 0
  }

  await fetchChatRoomMessages(roomId)

  nextTick(() => {
    scrollToBottom()
  })
}

// 新增状态变量
const isAiProcessing = ref(false)
const aiProcessingRoles = ref<string[]>([])
const lastUserMessageTime = ref<Date | null>(null)
const autoTalkTimer = ref<number | null>(null)
const activeWebSockets = ref<Map<string, WebSocket>>(new Map())

// 离开确认相关状态
const isInConversation = computed(() => {
  return isAiProcessing.value ||
         isSending.value ||
         activeWebSockets.value.size > 0 ||
         autoTalkTimer.value !== null
})

// 路由导航守卫状态
let routeGuardActive = false

const sendMessage = async () => {
  if (!messageInput.value.trim() || isSending.value || !currentRoomId.value || isAiProcessing.value) return

  // 用户发送消息时清除自动对话定时器
  if (autoTalkTimer.value) {
    clearTimeout(autoTalkTimer.value)
    autoTalkTimer.value = null
  }

  const content = messageInput.value.trim()
  messageInput.value = ''
  isSending.value = true

  try {
    // 先在本地显示消息
    const newMessage = {
      id: Date.now().toString(),
      content,
      userId: currentUserId.value,
      userName: userStore.profile?.nickname || userStore.profile?.username || '我',
      userAvatar: userStore.profile?.avatar,
      senderType: 0,
      timestamp: new Date()
    }

    if (!messages.value[currentRoomId.value]) {
      messages.value[currentRoomId.value] = []
    }
    messages.value[currentRoomId.value]?.push(newMessage)

    // 调用后端 API 发送消息
    const insertRequest: ChatRoomMessageInsertRequest = {
      roomId: currentRoomId.value,
      content: content,
      senderId: currentUserId.value,
      senderType: 0,
    }

    const response = await api.insertChatRoomMessage(insertRequest)

    if (response.data?.code === 0) {
      // 更新聊天室最后消息
      const room = chatRooms.value.find(r => r.id?.toString() === currentRoomId.value)
      if (room) {
        room.lastMessage = content
        room.lastMessageTime = new Date()
      }

      // 记录用户最后发送消息的时间
      lastUserMessageTime.value = new Date()

      await nextTick()
      scrollToBottom()

      // 启动AI对话流程
      await startAiConversationFlow()

      message.success('消息发送成功')
    } else {
      // 如果发送失败，移除本地消息
      const messageIndex = messages.value[currentRoomId.value]?.findIndex(m => m.id === newMessage.id)
      if (messageIndex !== undefined && messageIndex >= 0) {
        messages.value[currentRoomId.value]?.splice(messageIndex, 1)
      }
      message.error(response.data?.message || '消息发送失败')
    }
  } catch (error) {
    // 如果发送失败，移除本地消息
    const messageIndex = messages.value[currentRoomId.value]?.findIndex(m => m.id === Date.now().toString())
    if (messageIndex !== undefined && messageIndex >= 0) {
      messages.value[currentRoomId.value]?.splice(messageIndex, 1)
    }
    message.error('消息发送失败')
    console.error('发送消息失败:', error)
  } finally {
    isSending.value = false
  }
}

// 启动AI对话流程
const startAiConversationFlow = async () => {
  if (!currentRoomId.value || isAiProcessing.value) return

  try {
    isAiProcessing.value = true

    // 1. 获取可发言的AI角色列表
    const participationResponse = await api.getChatRoomRoleParticipation(currentRoomId.value)

    if (participationResponse.data?.code === 0 && participationResponse.data.data) {
      const roleParticipations = participationResponse.data.data

      // 2. 处理角色列表响应
      if (roleParticipations.length === 0) {
        // 若返回空列表：保持当前状态等待用户后续消息
        return
      }

      // 若返回非空列表：依次处理每个角色ID
      aiProcessingRoles.value = roleParticipations.map((rp: any) => rp.roleId || '').filter((id: string) => id)

      // 依次与每个角色进行对话
      for (const roleParticipation of roleParticipations) {
        if (roleParticipation.roleId) {
          await processAiRoleConversation(roleParticipation.roleId)
        }
      }

      // 3. 完成角色对话后的处理
      await handlePostAiConversation()

    } else {
      console.error('获取角色参与列表失败:', participationResponse.data?.message)
    }
  } catch (error) {
    console.error('AI对话流程失败:', error)
    message.error('AI对话流程失败')
  } finally {
    isAiProcessing.value = false
    aiProcessingRoles.value = []
  }
}

// 处理单个AI角色的对话
const processAiRoleConversation = async (roleId: string): Promise<void> => {
  return new Promise(async (resolve, reject) => {
    if (!currentRoomId.value || !authStore.token) {
      reject(new Error('缺少必要参数'))
      return
    }

    // 首先获取角色详细信息
    let roleInfo = null
    try {
      const roleResponse = await api.getChatRoomRoles(currentRoomId.value)
      if (roleResponse.data?.code === 0 && roleResponse.data?.data) {
        roleInfo = roleResponse.data.data.find((role: any) => role.id === roleId)
      }
    } catch (error) {
      // 处理错误
    }

    // 构建WebSocket URL
    const wsUrl = `wss://www.codewin.top/codewin/ai/chatroom/qwen-stream?token=${authStore.token}&chatRoomId=${currentRoomId.value}&roleId=${roleId}`

    try {
      const ws = new WebSocket(wsUrl)
      activeWebSockets.value.set(roleId, ws)

      let aiMessageContent = ''
      let aiMessageId = ''

      ws.onopen = () => {
        // WebSocket连接已建立
      }

      // 添加流结束检测定时器
      let streamEndTimer: number | null = null
      const STREAM_END_TIMEOUT = 2000 // 2秒无新数据则认为流结束

      ws.onmessage = (event) => {
        try {
          // 清除之前的结束检测定时器
          if (streamEndTimer) {
            clearTimeout(streamEndTimer)
            streamEndTimer = null
          }

          // 直接处理流式文本数据
          const textContent = event.data
          if (textContent && textContent.trim()) {
            // 处理流式文本消息
            if (!aiMessageId) {
              // 如果还没有创建AI消息，先创建一个
              aiMessageId = Date.now().toString() + '_' + roleId
              const aiMessage = {
                id: aiMessageId,
                content: textContent,
                userId: roleId,
                userName: roleInfo?.roleName || 'AI角色',
                senderType: 1,
                roleName: roleInfo?.roleName || 'AI角色',
                avatarUrl: roleInfo?.avatarUrl || '',
                timestamp: new Date()
              }

              if (!messages.value[currentRoomId.value!]) {
                messages.value[currentRoomId.value!] = []
              }
              messages.value[currentRoomId.value!]?.push(aiMessage)
              aiMessageContent = textContent
            } else {
              // 追加内容到现有消息
              aiMessageContent += textContent

              // 更新消息内容
              if (currentRoomId.value) {
                const messageList = messages.value[currentRoomId.value]
                if (messageList) {
                  const messageIndex = messageList.findIndex(m => m.id === aiMessageId)
                  if (messageIndex >= 0 && messageList[messageIndex]) {
                    messageList[messageIndex].content = aiMessageContent
                  }
                }
              }
            }

            nextTick(() => {
              scrollToBottom()
            })
          }

          // 设置新的结束检测定时器
          streamEndTimer = window.setTimeout(async () => {
            // AI角色流式对话完成

            // 在流结束时调用插入消息接口保存AI消息
            if (aiMessageContent && currentRoomId.value && roleInfo) {
              try {
                const insertRequest: ChatRoomMessageInsertRequest = {
                  roomId: currentRoomId.value,
                  content: aiMessageContent,
                  senderId: roleId,
                  senderType: 1, // AI角色
                }

                const response = await api.insertChatRoomMessage(insertRequest)
                if (response.data?.code !== 0) {
                  // 处理保存失败
                }
              } catch (error) {
                // 处理保存错误
              }
            }

            ws.close()
            resolve()
          }, STREAM_END_TIMEOUT)

        } catch (error) {
          // 即使出错也不要中断整个流程
        }
      }

      ws.onerror = (error) => {
        reject(error)
      }

      ws.onclose = () => {
        activeWebSockets.value.delete(roleId)
      }

      // 设置超时处理
      setTimeout(() => {
        if (ws.readyState === WebSocket.CONNECTING || ws.readyState === WebSocket.OPEN) {
          ws.close()
          reject(new Error('WebSocket连接超时'))
        }
      }, 30000) // 30秒超时

    } catch (error) {
      console.error(`创建WebSocket连接失败 - 角色ID: ${roleId}`, error)
      reject(error)
    }
  })
}

// 处理AI对话完成后的逻辑
const handlePostAiConversation = async () => {
  // 清除之前的自动对话定时器
  if (autoTalkTimer.value) {
    clearTimeout(autoTalkTimer.value)
    autoTalkTimer.value = null
  }

  // 设置30秒检测定时器
  autoTalkTimer.value = window.setTimeout(async () => {
    // 检查自动对话设置
    const currentRoomData = chatRooms.value.find(r => r.id?.toString() === currentRoomId.value)

    if (currentRoomData?.autoTalkEnabled === 1) {
      // 已开启自动对话：重新启动AI对话流程
      await startAiConversationFlow()
    }
    // 如果未开启自动对话，定时器结束，等待用户主动发送消息
  }, 30000)
}

// 清理WebSocket连接
const cleanupWebSockets = () => {
  activeWebSockets.value.forEach((ws, roleId) => {
    if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
      ws.close()
    }
  })
  activeWebSockets.value.clear()
}

const handleEnterKey = (event: KeyboardEvent) => {
  if (event.shiftKey) return
  event.preventDefault()
  sendMessage()
}

const handleTyping = () => {
  if (typingTimer) {
    clearTimeout(typingTimer)
  }

  typingTimer = window.setTimeout(() => {
    // 停止输入状态
  }, 2000)
}

const scrollToBottom = () => {
  if (chatContentRef.value) {
    chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
  }
}

const handleTranscriptionUpdate = (text: string, audioUrl: string) => {
  messageInput.value = text
  // 可以在这里处理音频文件，比如保存或上传
  console.log('语音转录完成:', text, '音频URL:', audioUrl)
}



// 处理角色选择提交
const handleRoleSelectionSubmit = async (selectedRoleIds: string[]) => {
  try {
    if (!currentRoomId.value) {
      message.error('请先选择聊天室')
      return
    }

    // 调用绑定角色接口
    const response = await api.bindChatRoomRoles({
      roomId: currentRoomId.value,
      roleIds: selectedRoleIds
    })

    if (response.data?.code === 0) {
      message.success('角色绑定成功')
      showRoleSelection.value = false
      // 可以在这里添加刷新聊天室信息的逻辑
    } else {
      message.error(response.data?.message || '角色绑定失败')
    }
  } catch (error) {
    console.error('角色绑定失败:', error)
    message.error('角色绑定失败，请重试')
  }
}

const handleRecordingStart = () => {
  isVoiceRecording.value = true
}

const handleRecordingStop = () => {
  isVoiceRecording.value = false
}

const handleVoiceError = (error: any) => {
  message.error('语音录制失败')
  isVoiceRecording.value = false
}

// 监听消息变化
watch(() => currentMessages.value.length, async () => {
  await nextTick()
  scrollToBottom()
})

// 路由离开守卫
const setupRouteGuard = () => {
  routeGuardActive = true

  // 监听浏览器返回按钮
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    if (isInConversation.value) {
      event.preventDefault()
      event.returnValue = '当前正在进行AI对话，离开页面将会中断对话进程。确定要离开吗？'
      return event.returnValue
    }
  }

  window.addEventListener('beforeunload', handleBeforeUnload)

  // 路由守卫
  const removeGuard = router.beforeEach(async (to, from, next) => {
    if (from.name === 'MultiChat' && isInConversation.value) {
      Modal.confirm({
        title: '确认离开页面',
        content: '当前正在进行AI对话，离开页面将会中断对话进程。确定要离开吗？',
        okText: '确定离开',
        cancelText: '取消',
        okType: 'danger',
        onOk() {
          // 重置对话状态
          resetConversationState()
          routeGuardActive = false
          window.removeEventListener('beforeunload', handleBeforeUnload)
          removeGuard()
          // 跳转到用户原先的目的地
          next(to)
        },
        onCancel() {
          next(false)
        }
      })
    } else {
      next()
    }
  })

  // 返回清理函数
  return () => {
    window.removeEventListener('beforeunload', handleBeforeUnload)
    removeGuard()
    routeGuardActive = false
  }
}

// 加载更多历史消息
const loadMoreMessages = async () => {
  if (!currentRoomId.value) return

  const pageInfo = messagePageInfo.value[currentRoomId.value]
  if (!pageInfo || pageInfo.loading || !pageInfo.hasMore) return

  // 记录当前滚动位置和第一条消息的位置
  const chatContent = chatContentRef.value
  if (!chatContent) return

  const firstMessage = chatContent.querySelector('.message-wrapper')
  const scrollTop = chatContent.scrollTop
  const scrollHeight = chatContent.scrollHeight

  await fetchChatRoomMessages(currentRoomId.value, true)

  // 恢复滚动位置，保持用户的阅读位置
  await nextTick()
  if (firstMessage) {
    const newScrollHeight = chatContent.scrollHeight
    const heightDiff = newScrollHeight - scrollHeight
    chatContent.scrollTop = scrollTop + heightDiff
  }
}

// 滚动事件处理
const handleScroll = () => {
  const chatContent = chatContentRef.value
  if (!chatContent || !currentRoomId.value) return

  // 检测是否滚动到顶部（留一些缓冲区域）
  if (chatContent.scrollTop <= 50) {
    loadMoreMessages()
  }
}

// 组件生命周期
onMounted(() => {
  // 初始化组件，获取聊天室列表
  fetchChatRooms()
  // 设置路由守卫
  const cleanup = setupRouteGuard()

  // 添加滚动监听器
  if (chatContentRef.value) {
    chatContentRef.value.addEventListener('scroll', handleScroll)
  }

  // 保存清理函数以便在组件卸载时调用
  ;(window as any).__multiChatCleanup = cleanup
})

// 组件卸载时清理资源
onUnmounted(() => {
  // 重置对话状态
  resetConversationState()

  // 移除滚动监听器
  if (chatContentRef.value) {
    chatContentRef.value.removeEventListener('scroll', handleScroll)
  }

  // 清理路由守卫
  if ((window as any).__multiChatCleanup) {
    ;(window as any).__multiChatCleanup()
    delete (window as any).__multiChatCleanup
  }
})

// 监听路由变化，清理资源
watch(() => router.currentRoute.value.path, () => {
  resetConversationState()
})

// 监听聊天室切换，清理相关资源
watch(currentRoomId, (newRoomId, oldRoomId) => {
  if (oldRoomId && oldRoomId !== newRoomId) {
    // 切换聊天室时重置对话状态
    resetConversationState()
  }
})
</script>

<style scoped>
/* 主容器 */
.multi-chat-container {
  display: flex;
  height: max(100vh, 1200px);
  background: #f8faff;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  margin: 0 auto;
  max-width: 1200px;
}

/* 左侧导航栏 */
.sidebar {
  width: 320px;
  background: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease;
}

.sidebar-hidden {
  transform: translateX(-100%);
}

/* 用户信息区域 */
.user-profile {
  padding: 24px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar-wrapper {
  position: relative;
}

.online-status {
  position: absolute;
  bottom: 2px;
  right: 2px;
  width: 12px;
  height: 12px;
  background: #10b981;
  border: 2px solid white;
  border-radius: 50%;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 2px;
}

.user-status {
  font-size: 12px;
  color: #10b981;
}

/* 创建聊天室按钮 */
.create-room-section {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.create-room-btn {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  border: none;
  border-radius: 12px;
  height: 48px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.create-room-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.create-room-btn:active {
  transform: scale(0.98);
}

/* 聊天室列表 */
.rooms-section {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.section-title {
  padding: 16px 20px 8px;
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.rooms-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px;
}

.room-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  margin-bottom: 4px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.room-item:hover {
  background: #f8faff;
}

.room-active {
  background: linear-gradient(135deg, rgba(99, 102, 241, 0.1) 0%, rgba(139, 92, 246, 0.1) 100%);
  border: 1px solid rgba(99, 102, 241, 0.2);
}

.room-avatar {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.room-content {
  flex: 1;
  min-width: 0;
}

.room-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.room-item:hover .room-actions {
  opacity: 1;
}

.room-actions .ant-btn {
  width: 28px;
  height: 28px;
  padding: 0;
  border: none;
  background: transparent;
  color: #6b7280;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.room-actions .ant-btn:hover {
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
}

.room-actions .ant-btn:focus {
  box-shadow: none;
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.room-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.room-time {
  font-size: 12px;
  color: #9ca3af;
}

.room-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  font-size: 13px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.unread-badge {
  background: #ef4444;
  color: white;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
}

/* 右侧主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

/* 顶部导航栏 */
.chat-header {
  height: 64px;
  padding: 0 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.online-roles-horizontal {
  flex-shrink: 0;
  max-width: 300px;
}

.current-room-info {
  flex-shrink: 0;
}

.sidebar-toggle {
  color: #6b7280;
}

.current-room-info {
  display: flex;
  flex-direction: column;
}

.room-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.room-members {
  font-size: 12px;
  color: #6b7280;
}

.settings-btn {
  color: #6b7280;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f8faff;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

/* Empty 组件样式 */
.empty-rooms {
  padding: 40px 20px;
  text-align: center;
}

.empty-description {
  color: #6b7280;
  font-size: 14px;
  margin-bottom: 8px;
}

.empty-tip {
  color: #9ca3af;
  font-size: 12px;
  margin-top: 8px;
}

.empty-state h3 {
  color: #374151;
  margin-bottom: 8px;
}

.empty-state p {
  color: #6b7280;
}

.messages-container {
  max-width: 800px;
  margin: 0 auto;
}

.message-wrapper {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.message-left {
  justify-content: flex-start;
}

.message-right {
  justify-content: flex-end;
}

.message-own {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 0 1 auto;
  max-width: fit-content;
}

.message-own .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-right .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.sender-name {
  font-size: 12px;
  font-weight: 500;
}

.message-time {
  font-size: 11px;
  color: #9ca3af;
}

.message-bubble {
  background: white;
  padding: 12px 16px;
  border-radius: 18px;
  border: 1px solid #e5e7eb;
  font-size: 14px;
  line-height: 1.4;
  color: #1f2937;
  word-wrap: break-word;
  display: inline-block;
  max-width: 100%;
  min-width: fit-content;
}

.bubble-user {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  border: none;
}

.bubble-ai {
  background: white;
  color: #1f2937;
  border: 1px solid #e5e7eb;
}

.message-time-user {
  font-size: 11px;
  color: #9ca3af;
  margin-top: 4px;
}

/* 正在输入指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: white;
  border-radius: 18px;
  border: 1px solid #e5e7eb;
  margin-bottom: 16px;
  max-width: fit-content;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.dot {
  width: 6px;
  height: 6px;
  background: #9ca3af;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

.typing-text {
  font-size: 12px;
  color: #6b7280;
}

/* 历史消息加载指示器 */
.loading-more-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #f8faff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e5e7eb;
  border-top: 2px solid #6366f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 12px;
  color: #6b7280;
}





/* 角色管理弹窗 */
.role-management {
  padding: 8px 0;
}

.role-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.role-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  background: #f8faff;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.role-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.role-user-details {
  display: flex;
  flex-direction: column;
}

.role-user-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.role-user-status {
  font-size: 12px;
  color: #6b7280;
}

.role-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mute-label {
  font-size: 12px;
  color: #6b7280;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: 0;
    top: 0;
    height: max(100vh, 1200px);
    z-index: 100;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  }

  .sidebar-hidden {
    transform: translateX(-100%);
  }

  .main-content {
    width: 100%;
  }

  .message-content {
    max-width: 85%;
  }

  .input-container {
    padding: 0 8px;
  }
}

@media (max-width: 480px) {
  .sidebar {
    width: 280px;
  }

  .chat-header {
    padding: 0 16px;
  }

  .chat-content {
    padding: 16px;
  }
}

/* AI处理状态指示器样式 */
.ai-processing-indicator {
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-top: 1px solid #e2e8f0;
  border-radius: 0 0 12px 12px;
  margin-top: 8px;
}

.processing-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #64748b;
  font-size: 14px;
}

.processing-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #e2e8f0;
  border-top: 2px solid #6366f1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.processing-text {
  font-weight: 500;
}

.processing-roles {
  color: #94a3b8;
  font-size: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
